package pacman.state;

import java.util.ArrayList;
import java.util.Collections;

import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.state.transition.FadeInTransition;
import org.newdawn.slick.state.transition.FadeOutTransition;

import pacman.util.ScoreRecord;
import pacman.util.ScoreTableLoader;

public class ScoreTable extends BasicGameState {

    public static final int ID = 5;
    private StateBasedGame sbg;
    private GameContainer gc;
    private ArrayList<ScoreRecord> scores;
    private int updateTimer;
    
    public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
    	this.sbg = sbg;
		this.gc = gc;
		updateTimer = 0;
		try {
		    ScoreTableLoader stl = new ScoreTableLoader("resources/scoretable.properties");
		    scores = new ArrayList<ScoreRecord>(stl.loadScoreTable());
		} catch (Exception e) {
	    	System.out.println(e.getMessage());
	    }
    }

    public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
    	g.drawString("Pacman Scoretable", 100, 50);
    	g.setColor(Color.red);	
    	int counter = 0;
    	Collections.sort(scores);

    	for (ScoreRecord score : scores) {
		    if (counter >= 20)
			break;
		    g.drawString(counter + " - " + score.getName(), 100, 90 + counter * 15);
		    g.drawString(score.getPoints().toString(), 300, 90 + counter * 15);
		    counter++;
    	}
		g.setColor(Color.white);
		g.drawString("Press enter to continue", 100, 500);
    }

    public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
		updateTimer = updateTimer + delta;
		if (updateTimer > 5000) {
		    try {
				ScoreTableLoader stl = new ScoreTableLoader( "resources/scoretable.properties");
				scores = new ArrayList<ScoreRecord>(stl.loadScoreTable());
		    } catch (Exception e) {
		    	System.out.println(e.getMessage());
		    }
		}
    }

    public void keyReleased(int key, char c) {
		if (key == Input.KEY_ENTER) {
		    sbg.enterState(Menu.ID, new FadeOutTransition(Color.black), new FadeInTransition(Color.black));
		}
		if (key == Input.KEY_F2) {
		    try {
			if (!gc.isFullscreen()) {
			    gc.setFullscreen(true);
			} else {
			    gc.setFullscreen(false);
			}
		    } catch (Exception e) {
		    	System.out.println(e.getMessage());
		    }
		}
    }
    @Override
    public int getID() {
    	return ID;
    }
}
